<?php
session_start();
include_once 'connect.php';

if (!isset($_SESSION['loginadmin'])) {
    die("0");
}

// 添加防重复提交检查
if (!isset($_POST['imgDatd']) || !isset($_POST['imgText'])) {
    die("0");
}

$imgDatd = trim($_POST['imgDatd']);
$imgText = trim($_POST['imgText']);
$uploadType = $_POST['uploadType'];

// 处理图片上传
if ($uploadType === 'local' && isset($_FILES['imageFile'])) {
    $file = $_FILES['imageFile'];
    
    // 验证文件类型
    $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($file['type'], $allowed)) {
        die("0"); // 不支持的文件类型
    }
    
    // 创建上传目录
    $upload_dir = '../uploads/images/' . date('Y/m/');
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // 生成文件名
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $extension;
    $filepath = $upload_dir . $filename;
    
    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        $imgUrl = str_replace('../', '/', $filepath);
    } else {
        die("0"); // 上传失败
    }
} else if ($uploadType === 'url') {
    $imgUrl = trim($_POST['imgUrl']);
    if (empty($imgUrl)) {
        die("0");
    }
} else {
    die("0");
}

// 检查是否已存在相同记录
$check_sql = "SELECT id FROM loveImg WHERE imgDatd = ? AND imgText = ? AND imgUrl = ? LIMIT 1";
$check_stmt = $connect->prepare($check_sql);
$check_stmt->bind_param("sss", $imgDatd, $imgText, $imgUrl);
$check_stmt->execute();
$check_result = $check_stmt->get_result();
if ($check_result->num_rows > 0) {
    die("2"); // 已存在相同记录
}
$check_stmt->close();

// 插入数据库
$sql = "INSERT INTO loveImg (imgDatd, imgText, imgUrl) VALUES (?, ?, ?)";
$stmt = $connect->prepare($sql);

if ($stmt) {
    $stmt->bind_param("sss", $imgDatd, $imgText, $imgUrl);
    if ($stmt->execute()) {
        echo "1";
    } else {
        echo "0";
    }
    $stmt->close();
} else {
    echo "0";
}

$connect->close();
?>
